package com.spark.incoicings.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spark.incoicings.service.*;
import com.spark.incoicings.vo.SupplierStatementVo;
import com.spark.invoicings.entity.*;
import com.spark.invoicings.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * 供应商对账单和明细
 *
 */
@RestController
@RequestMapping("/SalesReceipt")
public class SupplierStatementController {
    @Resource
    private SupplierStatementService sss;
    @Resource
    private ProcuredSupplierService pss;
    @Resource
    private SupplierStatementDetailService ssds;
    @Resource
    private ProductService ps;
    @Resource
    private ReceivablePayableDetailService rps;
    @Resource
    private OutboundDetailService outds;
    @Resource
    private InboundDetailService ids;
    @Resource
    private DictDataService ds;
    @Resource
    private WarehouseReceiptService wrs;
    @Resource
    private OutboundOrderService oos;

    /**
     * 分页条件查询客户对账单
     */
    @GetMapping("/selectSupplierStatement")
    public Result selectCustomerStatement(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize,
            @RequestParam(value = "supplierId", required = false) Integer supplierId) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("supplierId", supplierId);
        PageHelper.orderBy("supplier_statement_id desc");
        List<SupplierStatement> list = sss.selectSupplierStatements(map);
        for (SupplierStatement s : list) {
            s.setStatementDetails(ssds.selectSupplierStatementDetail(s.getSupplierStatementId()));
            s.setProcuredSupplier(pss.getById(s.getSupplierId()));
        }
        PageInfo<SupplierStatement> page = new PageInfo<>(list);
        return Result.success(200, "success", page);
    }

    @GetMapping("/selectProcuredSupplier")
    public Result selectProcuredSupplier(){
        List<ProcuredSupplier> list = pss.list();
        return Result.success(200, "success", list);
    }

    /**
     * 添加供应商对账单
     */
    @PostMapping("/saveSupplierStatement")
    @Transactional
    public Result saveSupplierStatement(@RequestBody SupplierStatementVo request) {
        SupplierStatement s = request.getSupplierStatement();
        List<SupplierStatementDetail> list = request.getStatementDetails();

        s.setBillNumber(generateBillNumber());
        sss.save(s);

        // 获取保存后的对账单ID
        int supplierStatementId = s.getSupplierStatementId();


        double totalAmount = 0; // 本期应收金额
        double currentReceivedAmount = 0; // 已收款总额
        double currentPendingAmount = 0; // 本期待收金额

        for (SupplierStatementDetail sd:list){
            totalAmount += sd.getTotalAmount();
            currentPendingAmount += sd.getPendingAmount();
            currentReceivedAmount += sd.getReceivedAmount();

            sd.setSupplierStatementId(supplierStatementId);
        }

        // 批量保存对账单明细
        ssds.saveBatch(list);

        // 更新客户对账单的金额信息
        s.setCurrentReceivableAmount(totalAmount);
        s.setCurrentReceivedAmount(currentReceivedAmount);
        s.setCurrentPendingAmount(currentPendingAmount);
        sss.updateById(s); // 更新客户对账单，MyBatis-Plus 的更新方法

        return Result.success();
    }

    private String generateBillNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String dateStr = sdf.format(new Date());

        // 查询今天已有的账单数量（假设从数据库查询，或者根据业务需要自定义逻辑生成）
        int existingBillCount = sss.count(); // 自定义方法，统计已有的账单数量

        // 生成新的账单编号，格式化为 KHDZ_YYMMdd_001, KHDZ_YYMMdd_002 等
        String billNumber = String.format("GYDZ_%s_%03d", dateStr, existingBillCount + 1);
        return billNumber;
    }

    /**
     * 根据供应商对账单id查询对应的对账单和明细
     * */
    @GetMapping("/selectSId")
    public Result selectSId(Integer supplierId){
        SupplierStatement s = sss.getById(supplierId);
        s.setStatementDetails(ssds.selectSupplierStatementDetail(s.getSupplierStatementId()));
        s.setProcuredSupplier(pss.getById(s.getSupplierId()));
        return Result.success(200,"success",s);
    }

    /**
     * 修改供应商对账单
     */
    @PostMapping("/updateSupplierStatement")
    public Result updateSupplierStatement(@RequestBody SupplierStatement supplierStatement) {
        sss.updateById(supplierStatement);
        return Result.success();
    }

    /**
     * 供应商对账单明细分页查询
     * */
    @GetMapping("/selectSupplierStatementDetail")
    public Result selectSupplierStatementDetail(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("supplier_statement_detail_id desc");
        List<SupplierStatementDetail> list = ssds.list();

        for (SupplierStatementDetail s : list) {
            // 设置 SupplierStatement
            s.setSupplierStatement(sss.getById(s.getSupplierStatementId()));

            // 设置 Product
            if (s.getProductId() != null) {
                Product product = ps.getById(s.getProductId());
                if (product != null) {
                    s.setProduct(product);
                }
            }

            // 设置 ReceivablePayableDetail
            s.setReceivablePayableDetail(rps.getById(s.getPurchaseOrderId()));
            ReceivablePayableDetail r = s.getReceivablePayableDetail();
            if (r != null) {
                // 设置 SettlementType 和 BusinessType
                r.setDictData(Arrays.asList(ds.getById(r.getSettlementTypeId()), ds.getById(r.getBusinessTypeId())));
            }

            // 设置 OutboundDetail
            s.setOutboundDetail(outds.getById(s.getOutboundId()));
            OutboundDetail outboundDetail = s.getOutboundDetail();
            if (outboundDetail != null) {
                outboundDetail.setOutboundOrder(oos.getById(outboundDetail.getOutboundOrderId()));
                outboundDetail.setProduct(ps.getById(outboundDetail.getProductId()));
            }

            // 设置 InboundDetail
            s.setInboundDetail(ids.getById(s.getInboundId()));
            InboundDetail inboundDetail = s.getInboundDetail();
            if (inboundDetail != null) {
                inboundDetail.setWarehouseReceipt(wrs.getById(inboundDetail.getInboundOrderId()));
                inboundDetail.setProduct(ps.getById(inboundDetail.getProductId()));
            }
        }

        PageInfo<SupplierStatementDetail> page = new PageInfo<>(list);
        return Result.success(200, "success", page);
    }


    /**
     * 根据供应商对账单明细id查询对应的对账单明细
     * */
    @GetMapping("/selectSupplierStatementDetailId")
    public Result selectSupplierStatementDetailId(Integer supplierStatementDetailId){
        SupplierStatementDetail s = ssds.getById(supplierStatementDetailId);
        // 设置 SupplierStatement
        s.setSupplierStatement(sss.getById(s.getSupplierStatementId()));

        // 设置 Product
        if (s.getProductId() != null) {
            Product product = ps.getById(s.getProductId());
            if (product != null) {
                s.setProduct(product);
            }
        }

        // 设置 ReceivablePayableDetail
        s.setReceivablePayableDetail(rps.getById(s.getPurchaseOrderId()));
        ReceivablePayableDetail r = s.getReceivablePayableDetail();
        if (r != null) {
            // 设置 SettlementType 和 BusinessType
            r.setDictData(Arrays.asList(ds.getById(r.getSettlementTypeId()), ds.getById(r.getBusinessTypeId())));
        }

        // 设置 OutboundDetail
        s.setOutboundDetail(outds.getById(s.getOutboundId()));
        OutboundDetail outboundDetail = s.getOutboundDetail();
        if (outboundDetail != null) {
            outboundDetail.setOutboundOrder(oos.getById(outboundDetail.getOutboundOrderId()));
            outboundDetail.setProduct(ps.getById(outboundDetail.getProductId()));
        }

        // 设置 InboundDetail
        s.setInboundDetail(ids.getById(s.getInboundId()));
        InboundDetail inboundDetail = s.getInboundDetail();
        if (inboundDetail != null) {
            inboundDetail.setWarehouseReceipt(wrs.getById(inboundDetail.getInboundOrderId()));
            inboundDetail.setProduct(ps.getById(inboundDetail.getProductId()));
        }
        return Result.success(200,"success",s);
    }

    /**
     * 添加供应商对账单明细
     * */
    @PostMapping("/saveSupplierStatementDetail")
    public Result saveSupplierStatementDetail(@RequestBody SupplierStatementDetail  sd){
        ssds.save(sd);
        return Result.success();
    }

    /**
     * 修改供应商对账单明细
     * */
    @PostMapping("/updateSupplierStatementDetail")
    public Result updateSupplierStatementDetail(@RequestBody SupplierStatementDetail  sd){
        ssds.updateById(sd);
        return Result.success();
    }
}
